import { createRouter, createWebHashHistory, RouteRecordRaw } from "vue-router";
import LoginVue from "@/views/login/index.vue";
import { userInfoApi } from "@/http/api";
import { useUserStore } from "@/store/user";
import { ElMessage } from "element-plus";
const routes: RouteRecordRaw[] = [
    {
      path: "/login",
      component: LoginVue,    
    },
    {
      path: "/",
      redirect: "/index",
    },
    {
      path: "/",
      component: () => import("../views/home/index.vue"),
      children: [
        {
          path: "index",
          component: () => import("../views/index/index.vue"),
        },
      ],
    },
  ];
  
  const router = createRouter({
    routes,
    history: createWebHashHistory(),
  });
  
router.beforeEach((to,from,next)=>{
  const store = useUserStore();
  let token = localStorage.getItem("token");
  if(store.menus.length===0&&token){
     userInfoApi().then((res)=>{
    if(res.code===200){
      store.menus=res.data.menus
      store.username=res.data.username
      store.routes.forEach((p)=>{
        const route:RouteRecordRaw = {
          path:"/"+p.name,
          name:p.name,
          component: ()=>import("../views/home/index.vue"),
          meta:{
            title:p.title
          },
          children:p.children.map(item=>({
            path:item.name,
            name:item.name,
            component: () => import(`../views/${p.name}/${item.name}.vue`),
            meta:{
              title:item.title
            },
          })),
      }
      if(p.children[0]){
        route.redirect = `/${p.name}/${p.children[0].name}`;
      }
         router.addRoute(route);
      });
      next(to.fullPath);
    }
  });
  }else if(!token && to.path!=='/login'){
      ElMessage.error('请先登录!');
      next('/login');
    }else if(token&&store.menus.length!==0&&to.path==='/login'){
      ElMessage.warning('请先退出登录在重新登录')
      next(from.fullPath)
    }
    else{
  next();
    }
});
  export default router;